const sha1 = require('sha1')
const getRawBody = require('raw-body')
const ejs = require('ejs')
const { wechatConfig } = require('../config/app')
const { ParseXML, FormatMessage, ToText, messageTpl } = require('../utils/wechatUtils')

module.exports = {
  //校验公众号参数
  verification: (req, res) => {
    let token = wechatConfig.token
    let { nonce, echostr, timestamp, signature } = req.query
    let str = [token, nonce, timestamp].sort().join('')
    let vasignature = sha1(str)
    if (vasignature === signature) return res.send(echostr)
    return res.send('')
  },

  //接收消息
  receiveMsg: async (req, res, next) => {
    //接收xml数据
    let xml = await getRawBody(req, {
      length: req.headers['content-length'],
      limit: '1mb',
      encoding: 'utf-8'
    })
    let result = await ParseXML(xml)
    //把接收的数据传递到下个中间件处理
    req.formatted = FormatMessage(result.xml)
    next()
  },

  //回复消息
  replyMsg: async (req, res, next) => {
    const formatted = req.formatted
    // console.log(formatted)
    switch (formatted.MsgType) {
      case 'text':
        res.send(ejs.render(await messageTpl(), ToText(formatted)))
        break
      case 'voice':
        formatted.Content = formatted.Recognition
        res.send(ejs.render(await messageTpl(), ToText(formatted)))
        break
      default:
        res.send('success')
        break
    }
  }
}